
//
//  AddContactPersonTool.m
//  AddContact
//
//  Created by MyMac on 15/10/29.
//  Copyright © 2015年 tongfang. All rights reserved.
//

#import "AddContactPersonTool.h"
#import <AddressBook/AddressBook.h>
#import <UIKit/UIKit.h>
@interface AddContactPersonTool()<UIAlertViewDelegate>{

    ABAddressBookRef addressBook;

}
@property(nonatomic,strong)NSMutableArray*personArray;

@end
@implementation AddContactPersonTool
+(instancetype)shareInstance{

    static AddContactPersonTool*tool=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool=[[AddContactPersonTool alloc]init];
        tool.personArray=[[NSMutableArray alloc]init];
    });
    return tool;

}
-(void)toolGetAddrssBookAllPeopleWithCompelet:(void(^)(NSMutableArray*personArray))personBlock{
    ABAuthorizationStatus state=ABAddressBookGetAuthorizationStatus();
    
    CFErrorRef error=nil;
     addressBook=ABAddressBookCreateWithOptions(NULL, &error);
    if (state!=kABAuthorizationStatusAuthorized) {
        NSLog(@"%@",[NSThread currentThread]);
        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"是否开放通讯录权限" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
        [alert show];
        return ;
    }
        
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            if (error) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"打开通讯录失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];

                });
                
            }else {
                if (granted) {
                    CFArrayRef arrayRef=ABAddressBookCopyArrayOfAllPeople(addressBook);
                    NSArray*person=(__bridge NSArray*)arrayRef;
                    for (NSUInteger i=0; i<person.count; i++) {
                        NSMutableDictionary*personDict=[NSMutableDictionary dictionary];
                        ABRecordRef record=CFBridgingRetain(person[i]);
                   CFStringRef nameStr=     ABRecordCopyCompositeName(record);
                 CFTypeRef firstStr=ABRecordCopyValue(record, kABPersonFirstNameProperty);
                CFTypeRef lastStr=ABRecordCopyValue(record, kABPersonLastNameProperty);
                CFTypeRef middleStr=ABRecordCopyValue(record, kABPersonMiddleNameProperty);
                        NSString*middleName=(__bridge_transfer NSString*)middleStr;
                        NSString*firstName=(__bridge_transfer NSString*)firstStr;
                        NSString*lastName=(__bridge_transfer NSString*)lastStr;
                NSString*name=(__bridge_transfer NSString*)nameStr;
                        if (name==nil) {
                            name=@"";
                        }
                        [personDict setObject:name forKey:@"姓名"];
                        if (firstName==nil) {
                            firstName=@"";
                        }
                        [personDict setObject:firstName forKey:@"姓"];
                        if (lastName==nil) {
                            lastName=@"";
                        }
                        [personDict setObject:lastName forKey:@"名"];
                        
                        if (middleName==nil) {
                            middleName=@"";
                        }
                        [personDict setObject:middleName forKey:@"中间名"];
                        NSString*firstProperty=(__bridge_transfer NSString*)ABRecordCopyValue(record,kABPersonFirstNamePhoneticProperty);
                        if (firstProperty==nil) {
                            firstProperty=@"";
                        }
                        [personDict setObject:firstProperty forKey:@"firstProperty"];
                        
                        int recordID=(int)ABRecordGetRecordID(record);
                    [personDict setObject:[NSNumber numberWithInt:recordID] forKey:@"recordID"];
                        
                        ABMultiValueRef valueRef=ABRecordCopyValue(record,kABPersonPhoneProperty);
                        NSUInteger phontCount=(NSUInteger)ABMultiValueGetCount(valueRef);
                        NSMutableArray*phoneArray=[NSMutableArray array];
                        for (NSUInteger j=0; j<phontCount; j++) {
                    CFTypeRef phone=ABMultiValueCopyValueAtIndex(valueRef, (CFIndex)j);
                    NSString*phoneNumber=(__bridge_transfer NSString*)phone;
                        [phoneArray addObject:phoneNumber];
                            
                        }
                        [personDict setObject:phoneArray forKey:@"电话"];
                        
                        ABMultiValueRef email=ABRecordCopyValue(record,kABPersonEmailProperty);
                        NSUInteger emailCount=(NSUInteger)ABMultiValueGetCount(email);
                        NSMutableArray*emailArray=[NSMutableArray array];
                        for (NSUInteger k=0; k<emailCount; k++) {
                            CFTypeRef emailType=ABMultiValueCopyValueAtIndex(email, (CFIndex)k);
                            NSString*emailNumber=(__bridge_transfer NSString*)emailType;
                            [emailArray addObject:emailNumber];
                            
                        }
                        [personDict setObject:emailArray forKey:@"email"];
                        
                      NSData*imageData=(__bridge_transfer NSData*)ABPersonCopyImageData(record);
                    UIImage*image=[UIImage imageWithData:imageData];
                if (image!=nil) {
            [personDict setObject:image forKey:@"image"];
        }
                        
                        [self.personArray    addObject:personDict];
                    }
        dispatch_sync(dispatch_get_main_queue(), ^{
                      personBlock(self.personArray);

                  });
        }else{
            dispatch_sync(dispatch_get_main_queue(), ^{
                UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提醒" message:@"请打开通讯录授权" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
                [alert show];

            });
            
                }
            }
            
    });


}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
 


}



@end
